package com.demo.springbootdemo.controller;

import cn.hutool.core.bean.BeanUtil;
import com.demo.springbootdemo.domain.dto.PageDTO;
import com.demo.springbootdemo.domain.dto.UserFormDTO;
import com.demo.springbootdemo.domain.po.User;
import com.demo.springbootdemo.domain.query.UserQuery;
import com.demo.springbootdemo.domain.vo.UserVO;
import com.demo.springbootdemo.service.IUserService;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户管理")
@RequestMapping("/users")
@RestController
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    @ApiOperation("新增用户")
    @PostMapping
    public void saveUser(@RequestBody UserFormDTO userDTO) {
        User user = BeanUtil.copyProperties(userDTO, User.class);
        userService.save(user);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("{id}")
    public void deleteUser(@ApiParam("用户id") @PathVariable("id") Long id) {
        userService.removeById(id);
    }

    @ApiOperation("根据id查询用户")
    @GetMapping("{id}")
    public UserVO getUser(@ApiParam("用户id") @PathVariable("id") Long id) {
//        User user = userService.getById(id);
//        return BeanUtil.copyProperties(user, UserVO.class);
        return userService.getByIdWithAddressList(id);
    }

    @ApiOperation("根据id集合查询用户")
    @GetMapping()
    public List<UserVO> getUser(@ApiParam("用户id集合") @RequestParam("ids") List<Long> ids) {
//        List<User> list = userService.listByIds(ids);
//        return BeanUtil.copyToList(list, UserVO.class);
        return userService.listByIdsWithAddressList(ids);
    }

    @ApiOperation("根据id扣减用户余额")
    @PutMapping("{id}/deduction/{money}")
    public void deductionById(
            @ApiParam("用户id") @PathVariable("id") Long id,
            @ApiParam("扣减金额") @PathVariable("money") int money
    ) {
        userService.deductById(id, money);
    }

    @ApiOperation("多条件查询用户")
    @GetMapping("query")
    public List<UserVO> queryUsers(UserQuery userQuery) {
        List<User> list = userService.queryUsers(
                userQuery.getName(), userQuery.getStatus(), userQuery.getMinBalance(), userQuery.getMaxBalance()
        );
        return BeanUtil.copyToList(list, UserVO.class);
    }

    @ApiOperation("多条件分页查询用户")
    @GetMapping("pages")
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {
        return userService.queryUsersPage(userQuery);
    }
}
